/**
 * $Id: ServletUtils.java 2 2011-09-03 10:16:43Z adriftrock@gmail.com $
 */

package com.swehr.servlet;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Rock Huang
 * @version 0.1
 */
public class ServletUtils {
    private static final Logger log = Logger.getLogger(ServletUtils.class);

    public static void printRequestInfo(HttpServletRequest req) {
        log.debug("{ method:" + req.getMethod() + ", servletPath:" +
                req.getServletPath() + ", requestURI:" + req.getRequestURI() +
                ", path:" + req.getPathInfo() + " }");
    }

    public static String getCookieValue(Cookie[] cookies, String cookieName) {
        for(Cookie c: cookies) {
            if (cookieName.equals(c.getName())) {
                return c.getValue();
            }
        }
        return null;
    }

    public static boolean toSignin(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Cookie[] c = req.getCookies();
        String email = null;
        if (c != null) {
            email = getCookieValue(c, "email");
        }
        if (email != null) {
            req.setAttribute("email", email);
            return false;
        } else {
            req.setAttribute("flash", "Please sign in");
            req.getRequestDispatcher("home.ftl").forward(req, resp);
            return true;
        }
    }

    public static void forward(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
            String target = req.getServletPath() + ".ftl";
            req.getRequestDispatcher(target).forward(req, resp);
    }
}
